﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CryptoFiles.Common;
using CryptoFiles.Data;
using CryptoFiles.Managers;

namespace CryptoFiles.Logic
{
    public class CryptoUser 
    {
        private string _login;
        private string _cryptoKey;

        public CryptoUser(string login)
        {
            using (CryptoDatabase db = new CryptoDatabase())
            {
                db.Connect();

                string key = db.GetUserKey(login);


                _cryptoKey = key;
                _login = login;

            }


            
        }


        public static void CreateNewUser(string login, string passwd, string repeatPasswd)
        {
            if (login == "")
                throw new UserRegistrationException("Пустое имя пользователя", ErrorType.EmptyLogin);

            if (passwd == "")
                 throw new UserRegistrationException("Пустой пароль", ErrorType.EmptyPasswd);

            if (passwd != repeatPasswd)
                throw new UserRegistrationException("Пароли не совпадают", ErrorType.PasswdMismatch);


            using (CryptoDatabase db = new CryptoDatabase())
            {
                db.Connect();
             
               
                string hashedPasswd = CryptoManager.GenerateHash(passwd);
                string cryptoKey = CryptoManager.GenerateKey();

                db.AddUser(login, hashedPasswd, cryptoKey);
            }

            FileManager.CreateUserDir(login);
   
        }


        public static bool CheckCredentials(string login, string passwd)
        {
            using (CryptoDatabase db = new CryptoDatabase())
             {
                 db.Connect();

                 passwd = CryptoManager.GenerateHash(passwd);

                 return db.CheckUserCredentials(login, passwd);
             }
        }

      

        public void SaveFile(string fileName, byte[] fileContent)
        {
            byte[] encryptedContent = CryptoManager.EncryptData(fileContent, _cryptoKey);

            CryptoFileInfo cryptoFileInfo = new CryptoFileInfo();
            cryptoFileInfo.FileName = fileName;
            cryptoFileInfo.FileContent = encryptedContent;
            cryptoFileInfo.Login = _login;

            FileManager.SaveFile(cryptoFileInfo);
        }



        public string[] GetFileList()
        {
            return FileManager.GetUserFileList(_login);
        }

        public byte[] GetFile(string fileName)
        {
            byte[] encryptedFile = FileManager.GetFile(_login, fileName);

            return CryptoManager.DecryptData(encryptedFile, _cryptoKey);
        }


        
    
    }
}
